package com.stu.stusystem.controller.netty;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.stu.stusystem.model.chat.ChatMsg;
import com.stu.stusystem.util.DateUtil;
import io.netty.channel.*;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.websocketx.*;
import io.netty.util.concurrent.GlobalEventExecutor;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author cxt
 * @date 2021/8/28
 * netty服务端请求处理类
 */
@Slf4j
public class NettyServerHandle extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    // 存储已经连接的对象
    public static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    // 存储用户id和用户的channelId绑定
    public static ConcurrentHashMap<String, ChannelId> userMap = new ConcurrentHashMap<>();

    // 用于存储群聊房间号和群聊成员的channel信息
    public static ConcurrentHashMap<String, ChannelGroup> groupMap = new ConcurrentHashMap<>();

    /**
     * 新建连接
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("新建连接{}", ctx.toString());
        // 添加到通道组中
        channelGroup.add(ctx.channel());
        super.channelActive(ctx);
    }


    /**
     * 接收到消息
     */
    @Override
    protected void messageReceived(ChannelHandlerContext ctx, TextWebSocketFrame textWebSocketFrame) throws Exception {
        String text = textWebSocketFrame.text();
        ObjectMapper mapper = new ObjectMapper();
        ChatMsg msg = mapper.readValue(text, ChatMsg.class);
        switch (msg.getSendType()) {
            case ChatMsg.SEND_TYPE_CONNECT:
                Channel channel = ctx.channel();
                break;
            case ChatMsg.SEND_TYPE_BROADCAST:
                System.out.println("广播");

                break;
            case ChatMsg.SEND_TYPE_GROUP:
                System.out.println("群聊");

                break;
            case ChatMsg.SEND_TYPE_PRIVATE:
                sendMsg(msg);
                ctx.writeAndFlush(new TextWebSocketFrame("[服务器接收到了客户端的消息-" + DateUtil.getStrTime(new Date()) + ":" + text));
                break;
        }
        // 发送回去
    }

    /**
     * 发送消息
     */
    public void sendMsg(ChatMsg msg) {
        // this.

    }

    /**
     * 关闭连接
     *
     * @param ctx 上下文对象，含有通道channel
     * @throws Exception
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        log.info("与客户端断开连接，通道关闭！");
        // 通道组移除
        channelGroup.remove(ctx.channel());
    }

    private static Integer getUrlParams(String url) {
        if (!url.contains("=")) {
            return null;
        }
        String userId = url.substring(url.indexOf("=") + 1);
        return Integer.parseInt(userId);
    }

}
